package com.orangesoft.tescherfriend.business.user.service.impl;

import java.util.List;

import cn.hutool.db.Page;
import com.orangesoft.common.entity.PageDTO;
import com.orangesoft.common.vo.ResultDTO;
import com.orangesoft.tescherfriend.business.user.dao.UserDao;
import com.orangesoft.tescherfriend.business.user.service.UserService;
import com.orangesoft.tescherfriend.business.user.entity.User;
import com.orangesoft.tescherfriend.business.user.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 用户
 *
 * @author xhy
 **/
@Service
public class UserServiceImpl implements UserService {

    private static Logger logger = LoggerFactory.getLogger(UserService.class);
    @Autowired
    private UserDao userDao;

    /**
     * 根据id获取唯一记录
     *
     * @param id
     * @return
     */
    @Override
    public User findById(Long id) {
        return userDao.findById(id).orElse(null);
    }

    /**
     * 获取全部记录
     *
     * @return
     */
    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }

    /**
     * 获取不分页数据，有查询条件，有排序
     *
     * @param userDTO
     * @return
     */
    @Override
    public List<User> findList(UserDTO userDTO) {
        return userDao.find(userDTO, false, userDTO.getSort(), userDTO.getOrder());
    }

    /**
     * 获取分页数据，有查询条件，有排序
     *
     * @param userDTO
     * @return
     */
    @Override
    public ResultDTO findPage(UserDTO userDTO) {
        List<User> list = userDao.find(userDTO, true, userDTO.getSort(), userDTO.getOrder());
        long count = userDao.count(userDTO);
        return ResultDTO.success(new PageDTO(list, count));
    }

    /**
     * 添加数据
     *
     * @param user
     * @return
     */
    @Override
    public User create(User user) {
        return userDao.save(user);
    }

    /**
     * 批量添加数据
     *
     * @param userList
     * @return
     */
    @Override
    public List<User> batchCreate(List<User> userList) {
        return userDao.saveAll(userList);
    }

    /**
     * 更新数据，更新数据前需要校验id是否为空
     *
     * @param user
     * @return
     */
    @Override
    public ResultDTO update(User user) {
        if (user.getId() != null) {
            return ResultDTO.success("", userDao.save(user));
        } else {
            return ResultDTO.failMsg("id不能为空，更新失败");
        }
    }

    /**
     * 删除数据，根据id做删除
     *
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        userDao.deleteById(id);
    }


    /**
     * 根据用户登录码查询用户
     *
     * @param userCode
     */
    @Override
    public List<User> findByUserCode(String userCode){
        return  userDao.findByUserCode(userCode);
    }
}
